﻿Imports System.Data.OleDb

Public Class addNew
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

        'Give the new picture a random name
        Dim newPictureName As String
        newPictureName = Guid.NewGuid().ToString() & getFormate(fup_picture.FileName)       'Give the random name, and it will not change the suffix of that image file
        If fup_picture.HasFile Then
            fup_picture.SaveAs(Server.MapPath("Pictures") & "/" & newPictureName)           'Put the picture in the Pictures Folder
        End If

        'This can connet to the Database
        Dim sql As String = "INSERT INTO SpiritList (spiritName, spiritPrice, percentageAlochol, producedIn, manufacturer, manuWebsite, picture, detail, uploadDate, diner_fkid) VALUES (@f1,@f2,@f3,@f4,@f5,@f6,@f8,@f9,@f10,@f11)"        'This is an SQL statment
        Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("SpiritConnString").ConnectionString)       'Connect to the Database
        Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)

        'The following statement can put the text in TextBox into the Database
        conn.Open()         'Open the databse
        cmd.Parameters.AddWithValue("@f1", tb_sName.Text)
        cmd.Parameters.AddWithValue("@f2", tb_sPrice.Text)
        cmd.Parameters.AddWithValue("@f3", tb_perAlochol.Text)
        cmd.Parameters.AddWithValue("@f4", tb_produecdIn.Text)
        cmd.Parameters.AddWithValue("@f5", tb_mName.Text)
        cmd.Parameters.AddWithValue("@f6", tb_mURL.Text)
        cmd.Parameters.AddWithValue("@f8", "Pictures/" & newPictureName)
        cmd.Parameters.AddWithValue("@f9", tb_details.Text)
        cmd.Parameters.AddWithValue("@f10", Format(Now(), "yyyy-MM-dd ") & Format(Now(), "HH:mm:ss"))    'Get the time of when user upload, this is for the function of show lastest uploaded spirit in the 'Home.aspx'
        cmd.Parameters.AddWithValue("@f11", User.Identity.Name)
        cmd.ExecuteNonQuery()
        conn.Close()        'Close the database

        cmd.Dispose()
        conn.Dispose()
        Response.Redirect("List.aspx")

    End Sub

    'This function can allow user to upload any formate of a picture
    Function getFormate(ByVal fileName As String)
        Dim fileParts = fileName.Split(".")         'Break up string by '.'
        Dim formate = fileParts(fileParts.Length - 1)       'Get the string after the last '.'   In other word, this will get the suffix of the file name
        Return "." & formate
    End Function
End Class